package com.itheima.stargraph.config;


import com.itheima.stargraph.api.ComfyuiApi;
import com.itheima.stargraph.handler.ComfyuiMessageHandler;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * Comfyui配置类
 *
 * @Author mr.zhang
 * Date 2025/6/8 20:49
 */
@Configuration
public class ComfyuiConfig {

    @Value("${comfyuiHost}")
    private String comfyuiHost;


    /**
     * 将ComfyuiApi注册为bean
     * @return
     */
    @Bean
    public ComfyuiApi comfyuiApi(){

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();
//        Usage of Kotlin internal declaration from different module
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(String.format("http://%s",comfyuiHost))
                .client(client)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        return retrofit.create(ComfyuiApi.class);
    }

    /**
     * 将消息处理ComfyuiMessageHandler注册为bean
     */
    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler){
        WebSocketClient webSocketClient = new StandardWebSocketClient();

//        String url = "ws://localhost:8188/ws?clientId=star-graph";
        String url = String.format("ws://%s/ws?clientId=star-graph",comfyuiHost);
        WebSocketConnectionManager webSocketConnectionManager = new WebSocketConnectionManager(webSocketClient, comfyuiMessageHandler, url);
        webSocketConnectionManager.start();
        return webSocketConnectionManager;
    }
}
